package site.shenjie.zuul.demo.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.micrometer.core.instrument.util.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.asn1.ocsp.ResponseData;
import site.shenjie.zuul.demo.tool.IpUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 沈杰
 * 2020-7-28 11:12:40
 * 过滤器：IP过滤器
 */
public class IpFilter extends ZuulFilter {
    // IP黑名单列表
    private List<String> blackIpList = Arrays.asList("127.0.1.1");

    public IpFilter() {
        super();
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("正在进行黑名单校验...");
        RequestContext ctx = RequestContext.getCurrentContext();
        String ip = IpUtils.getIpAddr(ctx.getRequest());
        ctx.set("sendToTwoLevel", "二级拦截器你好！我是一级拦截器！");
        // 在黑名单中禁用
        if (StringUtils.isNotBlank(ip) && blackIpList.contains(ip)) {
            ctx.setSendZuulResponse(false);
            Map<String, String> map = new HashMap<>();
            map.put("code", "500");
            map.put("message", "非法的请求");
            ctx.setResponseBody(JSONObject.toJSONString(map));
            ctx.getResponse().setContentType("application/json; charset=utf-8");
            // 拦截
            ctx.setSendZuulResponse(false);
            System.out.println("已进行拦截...");
            return null;
        }
        // 放行
        ctx.setSendZuulResponse(true);
        System.out.println("已允许通过...");
        return null;
    }
}
